/*
 * @Author: lys
 * @Description: 
 * @Date: 2024-02-22 19:10:50
 * @LastEditors: lys
 * @LastEditTime: 2024-05-12 00:26:09
 */
import axios from "axios";
import { message } from "ant-design-vue";
import storejs from "store"
import qs from "qs";
import { baseApi } from '@/config'
// 创建axios实例
const service = axios.create({
  // axios中请求配置有baseURL选项，表示请求URL公共部分  + process.env.VUE_APP_BASE_API
  // baseURL: process.env.VUE_APP_BASE_API,
  baseURL: baseApi,
  // 超时
  timeout: 60000,
});
// request拦截器
service.interceptors.request.use(
  (config) => {
    if (config.method === 'get') {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, { arrayFormat: 'repeat' })
      }
    }
    config.headers['Authorization'] = storejs.get("token") || ''
    config.headers['Content-Type'] = config.isUpload ? 'multipart/form-data' : 'application/json;charset=utf-8'
    // 是否需要设置 token
    return config;
  },
  (error) => {
    // console.log(error);
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (success) => {
    if (success.status === 200) {
      if (success.data.code === 0 || success.data.code === 200) {
        return success.data;
      }
      else if (success.data.code === 401) {
        // location.href = "/index";
        location.href = `${location.pathname}#/index`
      }
      else {
        message.error(success.data.msg);
        return Promise.reject(success.data.msg);
      }
    } else {
      message.error(success.data.msg);
      return Promise.reject(success.data.msg);
    }
  }
);

export default service;
